import microAppsCfg from '../config/microApps'
import { loadMicroApp, addGlobalUncaughtErrorHandler } from 'qiankun'
// 其他依赖。。。

const apps = microAppsCfg.map(app => ({
  ...app,
  entry: getEntry(app), // 把port转成微应用地址
  props: { baseUrl: app.activeRule, ...initialState }, // 传递给微应用的数据
  container: `.app_${app.name}--container`
}))

// 已激活的实例
const activeApps = {}
// 挂载app的方法
const mountMicroApp = path => {
  const app = apps.find(item => path.startsWith(item.activeRule))
  if (app) {
    const instance = activeApps[app.activeRule]
    if (instance) {
      instance.update()
    } else {
      activeApps[app.activeRule] = loadMicroApp(app) // 手动加载子应用
    }
  }
}
// 卸载app的方法
const unmountMicroApps = multipleTabsList => {
  for (const key in activeApps) {
    const isExist = multipleTabsList.some(
      tab => tab.url && tab.url.startsWith(key)
    )
    if (!isExist) {
      activeApps[key].unmount() // 手动卸载子应用
      delete activeApps[key]
    }
  }
}

export { mountMicroApp, unmountMicroApps }
